import { memo, useCallback, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  Affix,
  Button,
  Checkbox,
  Divider,
  Empty,
  Modal,
  Result,
  Spin,
} from 'antd';
import logo from '@/assets/logo.png';
import {
  cartCheckedState,
  cartShowState,
  cartStore,
  cartSumState,
  useCartStore,
} from '@/store/cartStore';
import {
  ExclamationCircleOutlined,
  MoneyCollectOutlined,
} from '@ant-design/icons';
import cn from 'classnames';
import QueueAnim from 'rc-queue-anim';
import { useRecoilValue } from 'recoil';
import NumberController from '@/components/NumberController';
import { formatUrl } from '@/utils/format';

import CartStruct = API.CartStruct;

const CartGroup: FC<PropsWithChildren<{ data: CartShow }>> = ({ data }) => {
  return (
    <div className={'py-2'}>
      <div className={'flex items-start py-2 text-base '}>
        <img className={'w-5 h-5 mx-0.5'} src={logo} alt="" />{' '}
        <span className={'font-serif mr-2'}>商家:</span>{' '}
        <Link to={`/user_page/` + data.id}>{data.name}</Link>
      </div>
      <QueueAnim
        type={['right', 'left']}
        component={'ul'}
        appear={false}
        className={'bg-blue-50 rounded-3xl overflow-hidden border'}
      >
        {data.carts.length > 0
          ? data.carts.map((value) => (
              <li key={value.id}>
                <CartItem key={value.id} data={value} />
              </li>
            ))
          : null}
      </QueueAnim>
    </div>
  );
};

const CartItem: FC<PropsWithChildren<{ data: CartStruct }>> = ({ data }) => {
  const navigate = useNavigate();
  const { checkCart, deleteCart, changeCartNum } = useCartStore();
  const onChange = useCallback((id: number) => {
    return (value: number) => {
      changeCartNum(id, { num: value });
    };
  }, []);
  return (
    <div
      className={cn(
        'flex items-start justify-between p-5 text-center transition',
        {
          'bg-blue-100': data.is_checked,
        }
      )}
    >
      <div className={'w-[8%]'}>
        <Checkbox
          checked={Boolean(data.is_checked)}
          onClick={() => {
            checkCart({ cart_ids: [data.id] });
          }}
        />
      </div>
      <div
        className={'flex flex-1 mx-16 cursor-pointer'}
        onClick={() => {
          navigate(`/goods_detail/` + data.goods_id);
        }}
      >
        <img
          className={'w-16 h-22'}
          src={formatUrl(data.goods?.cover!)}
          alt=""
        />
        <div className={'text-left'}>
          <div className={'px-4 pb-2 pt-3 space-y-1.5'}>
            <div className={'text-base truncate'}>{data.goods?.title}</div>
            <div className={'truncate-2 text-sm'}>
              {data.goods?.description}
            </div>
          </div>
        </div>
      </div>
      <div className={'space-y-2 w-[12%]'}>
        <div>
          <i className={'line-through text-gray-600'}>
            <em className={'text-xs px-0.5'}>￥</em>
            {data.goods?.discount! < 1 ? data.goods?.price : null}
          </i>
        </div>
        <div>
          <strong className={'text-blue-600 text-lg'}>
            <em className={'text-xs px-0.5'}>￥</em>
            {data.goods?.price! * data.goods?.discount!}
          </strong>
        </div>
      </div>
      <div className={'w-[12%]'}>
        <NumberController data={data} onChange={onChange(data.id)} />
      </div>
      <div className={'text-lg w-[12%] text-red-500 font-bold font-serif'}>
        <em className={'text-xs px-0.5'}>￥</em>
        <span>{data.num * data.goods?.price! * data.goods?.discount!}</span>
      </div>
      <div className={'w-[12%]'}>
        <Button
          type={'link'}
          onClick={() => {
            Modal.confirm({
              title: '删除',
              icon: <ExclamationCircleOutlined />,
              content: '确认要删除该物品吗',
              okText: '确定',
              okType: 'danger',
              cancelText: '取消',
              onOk() {
                deleteCart({ cart_ids: [data.id] });
              },
              onCancel() {},
            });
          }}
        >
          删除
        </Button>
      </div>
    </div>
  );
};

const CartBar: FC<PropsWithChildren<{}>> = () => {
  const cartCheckedNum = useRecoilValue(cartCheckedState);
  const cartSum = useRecoilValue(cartSumState);
  const carts = useRecoilValue(cartStore);
  const { deleteCart } = useCartStore();
  const navigate = useNavigate();
  return (
    <Affix offsetBottom={0}>
      <div
        className={'flex items-center justify-between p-5 border-t bg-white'}
      >
        <div className={'flex-justify-items-center'}>
          <CartAllChecked />
          <Button
            type={'link'}
            onClick={() => {
              Modal.confirm({
                title: '删除',
                icon: <ExclamationCircleOutlined />,
                content: '确认要删除该物品吗',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  deleteCart({
                    cart_ids: carts.map(
                      (value) => value.is_checked && value.id
                    ),
                  });
                },
                onCancel() {},
              });
            }}
          >
            删除
          </Button>
        </div>
        <div className={'text-base flex-justify-items-center'}>
          <div className={'flex-justify-items-center'}>
            已选商品
            <span className={'text-lg px-2 font-bold text-red-500'}>
              {cartCheckedNum}
            </span>
            件
          </div>
          <div className={'mx-4 flex-justify-items-center'}>
            合计（不含运费）
            <span className={'text-2xl px-2 font-bold text-red-500'}>
              {cartSum.toFixed(2)}
            </span>
          </div>
          <Button
            type={'primary'}
            icon={<MoneyCollectOutlined />}
            disabled={cartCheckedNum <= 0}
            onClick={() => {
              navigate('/orders');
            }}
          >
            结 算
          </Button>
        </div>
      </div>
    </Affix>
  );
};

const CartAllChecked: FC<PropsWithChildren<{}>> = () => {
  const cartCheckedNum = useRecoilValue(cartCheckedState);
  const nativeCart = useRecoilValue(cartStore);
  const { checkCart } = useCartStore();
  return (
    <Checkbox
      checked={nativeCart.length === cartCheckedNum}
      onChange={() => {
        checkCart({
          cart_ids: nativeCart.map((value) => value.id),
          checked: true,
          reverse: nativeCart.length === cartCheckedNum,
        });
      }}
    >
      全选
    </Checkbox>
  );
};

const CartPage: FC<PropsWithChildren<{}>> = () => {
  const carts = useRecoilValue(cartShowState);
  const nativeCart = useRecoilValue(cartStore);

  return (
    <section className={'w-[1200px] p-12 m-auto min-h-screen'}>
      <section className={'rounded-3xl overflow-hidden bg-white'}>
        <div
          className={
            'text-xl border-b p-5 font-serif tracking-wider flex items-center font-bold'
          }
        >
          购物车 (全部
          <span className={'text-blue-600 px-1'}>{nativeCart.length}</span>)
        </div>
        <div className={'px-5 py-3'}>
          <div className={'flex  items-center justify-between text-center'}>
            <div className={'w-[8%]'}>
              <CartAllChecked />
            </div>
            <div className={'flex-1'}>商品信息</div>
            <div className={'w-[12%]'}>单价</div>
            <div className={'w-[12%]'}>数量</div>
            <div className={'w-[12%]'}>金额</div>
            <div className={'w-[12%]'}>操作</div>
          </div>
          <div className={'mt-3'}>
            {carts ? (
              carts.length > 0 ? (
                carts.map((value) => <CartGroup key={value.id} data={value} />)
              ) : (
                nativeCart.length > 0 && <Empty />
              )
            ) : (
              <Spin />
            )}
          </div>
        </div>
        <CartBar />
      </section>
    </section>
  );
};

export default memo(CartPage);
